#!/usr/bin/env python
#coding=utf-8
import os
import Model
import View
import wx
import Globals
import Casing
class Controller:
    def __init__(self, app):
        self.model = Model.Model()
        self.model.observable.addCallback(self.OnGotTreeData)
        self.__symbol = Globals.GetTransforSymbol()
        self.__currPageNO = 1
        self.__currBoradName = ""
        self.view = View.View() 
        self.view.Bind(View.EVT_LEFTTREE_CREATED,self.onLeftTreeCreated)   
        self.view.CreateLeftTree()     
        self.view.Bind(View.EVT_RIGHTTREE_CREATED,self.onRightTreeCreated)       
        self.view.splitter.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING, self.OnSashChanging)            
        self.view.search.Bind(wx.EVT_TEXT_ENTER, self.OnDoSearch)      
        self.view.search.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN,self.OnSeatchCancel)      
        self.view.search.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.OnDoSearch)   
        self.view.Bind(wx.EVT_BUTTON, self.OnEnterBorad, self.view.enterbtn)
        self.view.Bind(wx.EVT_BUTTON, self.OnHideButton, self.view.hidebtn)
        self.view.Bind(wx.EVT_BUTTON, self.OnRefreshBtnClick, self.view.refreshBtn)
        self.view.Bind(wx.EVT_RADIOBOX, self.OnEvtRadioBox, self.view.rbDisplayModel)
        self.DisplayKind = self.view.rbDisplayModel.GetSelection()
        for name in self.model.GetBoradTexts():
            self.view.enterChoice.Append(name)
        buttonData = {u"<<第一页": self.OnNavagiteBtnClick,u"<上一页": self.OnNavagiteBtnClick,u">下一页": self.OnNavagiteBtnClick}
        for i in self.view.pageButtonPnl.GetChildren():
            if (i.ClassName =="wxButton"):
                self.view.Bind(wx.EVT_BUTTON,buttonData[i.GetLabel()],i) 
        app.SetTopWindow(self.view)        
        self.view.Show(True)
        def f():
            try:
                self.model.GetNewBoradData()
            except:
                pass
        d = Casing.Casing(f)
        d.start_thread()
    def OnRighttTreeDBClick(self,event):
        strTemp = self.view.rightTree.GetItemDataByEvent(event)[8]
        self.view.detailPage.SetPage("")
        self.view.detailPage.SetPage(strTemp)
        event.Skip(False)   
        
    def OnLeftTreeDBClick(self,event):
        item,value =  self.view.leftTree.HitTest(event.GetPosition())
        if item !=None:
            busy = wx.BusyInfo(u"正在创建帖子树！请稍等……")
            strText = item.GetText()
            if(self.view._MyFlag == True):
                self.view.rightTree.Destroy() 
            self.view.CreateRightTree(self.DisplayKind)
            self.__currBoradName =strText
            self.__currPageNO = 1
            self.model.SetBoradNamePage(self.__currBoradName,self.__currPageNO)
            busy.Destroy()
        event.Skip(False)
    def OnNavagiteBtnClick(self,event):
        #如果没有创建树，则导航按钮无效~
        try:
            self.view.rightTree
        except:
            return
        if self.__currPageNO >= 1:
            if event.GetEventObject().GetLabel() ==u"<<第一页":
                if self.__currPageNO >1:
                    self.__currPageNO = 1
            elif event.GetEventObject().GetLabel() ==u"<上一页":
                self.__currPageNO = self.__currPageNO - 1
                if self.__currPageNO ==0:
                    self.__currPageNO = 1;
                    return
            else:
                self.__currPageNO = self.__currPageNO + 1
            self.DoCreateTree()
        event.Skip() 
    
    def DoCreateTree(self):
        busy = wx.BusyInfo(u"正在创建帖子树！请稍等……")
        self.view.CreateRightTree(self.DisplayKind)
        self.model.SetBoradNamePage(self.__currBoradName,self.__currPageNO)
        busy.Destroy()
        
    #进入版面事件
    def OnEnterBorad(self,evt):
        boradName = self.view.enterChoice.GetLabelText() 
        if boradName != '':
            if self.view._MyFlag == True:
                self.view.rightTree.Destroy()  
            self.__currPageNO = 1
            self.__currBoradName = boradName;
            self.DoCreateTree()
        evt.Skip()
    #刷新按钮
    def OnRefreshBtnClick(self,event):
        def f():
            rtn = self.model.GetNewMessages(self.OnReceiveCallBack)
            self.view.statusbar.SetStatusText(u"共有"+str(rtn[0])+u"条数据要更新,更新失败"+str(rtn[1])+u"条！", 1)
        d = Casing.Casing(f)
        d.start_thread()        
        
    def OnReceiveCallBack(self,regs):
        self.view.statusbar.SetStatusText(u"共有"+str(regs[0])+u"条数据要更新,已经更新"+str(regs[1])+u"条！", 1)
    #隐藏按钮
    def OnHideButton(self, event): 
        if self.view.hidebtn.GetText() == u'隐藏导航':
            strName = "bp_btn2.png"
            self.view.splitter.SetSashPosition(1)
        else:
            strName = "bp_btn1.png"
            self.view.splitter.SetSashPosition(150)
        self.view.p2.Layout()
        png = wx.Image(os.path.join(Globals.GetCurrDir(), 'img', strName),wx.BITMAP_TYPE_PNG).ConvertToBitmap()
        self.view.hidebtn.SetBitmap(png,status="Normal")
        self.view.hidebtn.SetText(self.view.toolBtnNames[strName])
        event.Skip()
    def onLeftTreeCreated(self,event):
        tree = event.GetEventArgs()
        tree.Bind(wx.EVT_LEFT_DCLICK,self.OnLeftTreeDBClick)
        root = tree.GetRootItem()
        for i in self.model.boradData:
            child = tree.AppendItem(root,i[1])
            tree.SetItemImage(child,1, wx.TreeItemIcon_Normal)
            tree.SetItemImage(child,2, wx.TreeItemIcon_Selected)
        tree.Expand(root)
    #准备好数据后的回调函数，开始构建树
    def OnGotTreeData(self,data):
        tree = self.view.rightTree
        root = tree.AddRoot("   ")#,data=[0,1]
        tree.SetItemPyData(root,[0,1])
        #开始构建树由主帖ID创建帖子，递归调用 
        def CreateTree(Item,tree):
            ItemID = tree.GetItemPyData(Item)[0]
            for si in data:
                if si[1] == ItemID:
                    strWordCount = si[7] and  str(si[7])+u'字' or u'空'
                    strTitle = si[3]
                    for k,v in self.__symbol.items():
                        strTitle = strTitle.replace(k,v)            
                    imgID = str(si[9]) != '0' and int(self.view.imgDataDict[str(si[9])]) or -1
                    SubItem = tree.AppendItem(Item,strTitle,imgID,imgID,strWordCount,si[4],str(si[5]),si[6])
                    tree.SetItemPyData(SubItem,si)
                    CreateTree(SubItem,tree)            
        CreateTree(root,tree)
        tree.ExpandAll(root)      
          
    #由于RightTree不是开始就创建的，所以在__init__里面rightTree对象还没有创建。
    #所以只能通过自定义事件来告诉Controller，在创建了对象之后再banding
    def onRightTreeCreated(self,event):
        tree = event.GetEventArgs()
        tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnRighttTreeDBClick)
        tree.Bind(wx.EVT_LEFT_DCLICK,self.OnRighttTreeDBClick)

    #分割条滑动事件
    def OnSashChanging(self, evt):
        self.view.splitter.Layout()
        self.view.p2.Layout()
    def OnEvtRadioBox(self,evt):
        try:
            self.view.rightTree
        except:
            return        
        if self.DisplayKind!=evt.GetInt():
            self.DisplayKind = evt.GetInt()
            self.view.CreateRightTree(self.DisplayKind)
            self.OnGotTreeData(self.model.GetCurrentData())
            #self.DoCreateTree()

    #查询事件    
    def OnDoSearch(self, evt):
        dlg = wx.MessageDialog(self.view, '对不起，此功能正在开发中！','提示信息',wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()
        
    #查询取消事件
    def OnSeatchCancel(self, evt):
        self.view.search.SetValue('')
        
